package com.mxq.eclipse.mqtt.demo.publish;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 发布客户端连接
 *
 * @author xiaoqiang
 * @date 2020-05-09 17:24
 */
@Component
public class PublishConnect {

    @Value("${mqtt.broker}")
    private String broker;

    public MqttClient connectMqttClient(MqttPublishDto mqttPublishDto, MqttConnectOptions mqttConnectOptions) throws MqttException {
        // 内存存储
        MemoryPersistence persistence = new MemoryPersistence();
        // 创建客户端
        MqttClient sampleClient = new MqttClient(broker, mqttPublishDto.getClientId(), persistence);
        // 在重新启动和重新连接时记住状态
        mqttConnectOptions.setCleanSession(false);
        // 设置回调
        sampleClient.setCallback(new PublishCallback());
        // 建立连接
        sampleClient.connect(mqttConnectOptions);
        return sampleClient;
    }
}